﻿using System;
using System.Collections.Generic;
using System.Text;
using IPNumbers;
using System.Xml;
using System.Text.RegularExpressions;

namespace GateKeeper
{
    public static class CheckIPAddress
    {
        /// <summary>
        /// Check if the IPAddress already exists
        /// </summary>
        public static Boolean IPEntryExists(XmlDocument document, string value)
        {
            Regex maskExpression = new Regex("(?<ip>[0-9.]*)/(?<mask>\\d+)", RegexOptions.Compiled);
            
            //TODO:  Need to load the IPList into cache to avoid loading each page load...
            IPList iplist = new IPList();

            XmlNodeList entryNodes = document.SelectNodes("/gatekeeper/ipaddress/entry");
            foreach (XmlNode xnode in entryNodes)
            {
                string address = xnode.Attributes[@"ipaddress"].Value;
                Match m = maskExpression.Match(address);
                if(m.Success)
                    iplist.Add(m.Groups["ip"].ToString(), int.Parse(m.Groups["mask"].Value));
                else
                    iplist.Add(address);
            }

            return iplist.CheckNumber(value);


            //XmlNode node = document.SelectSingleNode(string.Format("/gatekeeper/ipaddress/entry[@ipaddress='{0}']", value));
            //GateKeeperModule.log.DebugFormat((node != null) ? "IP Address found" : "IP Address not found");
            //return (node != null);
        }

    }
}
